package controller

import (
	"log"
	"regexp"
	"writerhelper/model"
	"writerhelper/service"

	"github.com/gin-gonic/gin"
)

func Register(rg *gin.RouterGroup) {
	rg.POST("register", RegisterHandle)
}

func RegisterHandle(c *gin.Context) {
	var user model.User
	var create bool
	//test := c.PostForm("email")
	//fmt.Println(test)
	if err := c.Bind(&user); err != nil {
		log.Fatal("绑定表单出现问题", err)
	}
	//进行数据验证
	//正则表达式^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$
	myRegexp := `^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`

	match, _ := regexp.MatchString(myRegexp, user.Email)
	if !match {
		c.JSON(200, map[string]interface{}{
			"code":    "错误代码",
			"message": "传入的邮箱格式不符合要求。",
		})
		return
	} else {
		//
		create = service.RegisterService(&user)
	}
	if create {
		c.JSON(200, map[string]interface{}{
			"code":    "创建成功",
			"message": "创建成功",
		})
	} else {
		c.JSON(200, gin.H{
			"code":    "创建失败",
			"message": "可能是用户名重复，也可能是其他原因",
		})
	}

}
